package org.example.aaaatest.a11;

import lombok.extern.slf4j.Slf4j;
import net.iakovlev.timeshape.TimeZoneEngine;
import org.apache.commons.collections4.CollectionUtils;


import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.TimeZone;

/**
 * @Classname TimeZoneUtil
 * @Description 国际化时区工具类
 * @Date 2025/3/14 15:37
 * @Created by fankaiqiang
 */
@Slf4j
public class TimeZoneUtil {

    private static TimeZoneEngine engine = TimeZoneEngine.initialize();


    /**
     * 根据客户端公参i18n_tz_offset，获取时区对象
     * 如：i18n_tz_offset=28800 000，则返回东8区时区对象
     */

    public static TimeZone getTimeZone(Integer i18n_tz_offset) {
        if (Objects.isNull(i18n_tz_offset)) {
            //入参为空，则返回东八区默认时区
            return TimeZone.getDefault();
        }
        i18n_tz_offset = i18n_tz_offset / (1000 * 60);
        int hours = i18n_tz_offset / 60;
        int minutes = i18n_tz_offset % 60;
        ZoneId zoneId = ZoneOffset.ofHoursMinutes(hours, minutes);

        return TimeZone.getTimeZone(zoneId);

    }


    /**
     * 根据客户端公参i18n_tz_offset，获取时区对象
     * 如：i18n_tz_offset=28800 000，则返回东8区时区对象
     */


    /**
     * 根据经纬度获取时区行政时区
     *
     * @param lat 纬度
     * @param lng 经度
     * @return 时区
     */
    public static TimeZone getAdminTimeZone(double lat, double lng) {
        try {
            List<ZoneId> zoneIds = engine.queryAll(lat, lng);
            if (CollectionUtils.isNotEmpty(zoneIds)) {
                return TimeZone.getTimeZone(zoneIds.get(0));
            }
            return TimeZone.getDefault();
        } catch (Exception e) {
            log.error("getAdminTimeZone error", e);
            return TimeZone.getDefault();
        }
    }


    /**
     * 将 ZoneOffset 格式化为 UTC±HH:mm 字符串
     */
    public static String formatZoneOffsetToUTC(ZoneOffset offset) {
        // 获取总秒数并计算小时、分钟
        int totalSeconds = offset.getTotalSeconds();
        int hours = totalSeconds / 3600;
        int minutes = Math.abs((totalSeconds % 3600) / 60);

        // 格式化为 GMT±HH:mm（小时补两位，分钟补两位）
        return String.format("UTC%+03d:%02d", hours, minutes);
    }


    /**
     * 将 ZoneId 格式化为 GMT±HH:mm 字符串
     */
    public static String formatZoneIdToUTC(TimeZone timeZone) {
        return formatZoneOffsetToUTC(ZonedDateTime.now(timeZone.toZoneId()).getOffset());
    }


    /**
     * 将日期时间字符串转换为 Unix 毫秒数
     *
     * @param dateTime  日期时间字符串，格式为 "yyyy-MM-dd HH:mm:ss"
     * @param utcOffset UTC 偏移量，格式为 "UTC+08:00"
     * @return
     */
    public static long dateTimeToUnixMillis(String dateTime, String utcOffset) {
        if (dateTime == null || dateTime.trim().isEmpty() || utcOffset == null || utcOffset.trim().isEmpty()) {
            throw new IllegalArgumentException("Date-time string and UTC offset cannot be null or empty.");
        }
        try {
            String realUtcOffset = utcOffset.replace("UTC", "");
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime localDateTime = LocalDateTime.parse(dateTime, formatter);
            ZoneOffset offset = ZoneOffset.of(realUtcOffset);
            OffsetDateTime offsetDateTime = OffsetDateTime.of(localDateTime, offset);
            return offsetDateTime.toInstant().toEpochMilli();
        } catch (DateTimeParseException e) {
            throw new IllegalArgumentException("Invalid date-time format: " + dateTime, e);
        } catch (DateTimeException e) {
            throw new IllegalArgumentException("Invalid UTC offset: " + utcOffset, e);
        }
    }


}
